<?php

class DataBase{
  var $Connexion 	= 0;
  var $Resultat 	= 0;
  var $Count 		= 0;		// Nombre de ligne d'une requête
  var $lastId 		= 0;		// Id dernière ligne d'un INSERT avec auto_increment
  var $UTF8			= true;	// Renvoyer de l'utf 8?
  var $dbName 		= ''; 		// Nom de la base sur laquelle on est connecté
  
  protected static $_tables       = array();
  protected static $_tablePrefix  = '';
  
    /**
     *  set the tablesNames who needs to be prefixed
     * @param array $tables 
     */
    public static function setTablesNames($tables = array()){
      self::$_tables = $tables;
    }
    
    /**
     * get the tables names who needs to be prefixed
     * @return array 
     */
    public static function getTablesNames(){
      return self::$_tables;
    }
    
    public static function setTablePrefix($prefix){
      self::$_tablePrefix = $prefix;
    }
    
    public static function getTablePrefix(){
      return(self::$_tablePrefix);
    }
    
    
    public static function stripslashes_sql($row){
      if(!is_array($row)){
          return stripslashes($row);
      }

      foreach($row as $key=>$val){
          $row[$key]=stripslashes($val);	
      }
      return $row;
    }
    
    public static function addslashes_sql($row){
      if(!is_array($row)){
        return addslashes($row);
      }

      foreach($row as $key=>$val){
        $row[$key]=addslashes($val);	
      }
      return $row;
    }

    public static function enc_utf8(&$val,$key){
      $val=utf8_encode($val);
    }

    public static function dec_utf8(&$val,$key){
      $val=utf8_decode($val);
    }
  
 	function __construct($db_name,$user='',$pwd='',$serveur='',$UTF8=true){
 	
 		if(!isset($user) || $user==''){
 			$user="root";
 			$pwd="";
 		}

 		if(!isset($serveur) || $serveur=='')
            $serveur='localhost';
            
		$this->dbName=$db_name;
        $this->Connexion = mysql_pconnect($serveur, $user, $pwd) or exit ("connecte pas");

		$this->UTF8=$UTF8;
		mysql_select_db($db_name, $this->Connexion) or exit ("select pas");
	}

	function _query(&$sql){
		$Requetes=array();
        
		$this->PMA_splitSqlFile($Requetes,$sql);
        
        array_unshift($Requetes,array('query'=>"SET CHARACTER SET 'utf8'"));
        array_unshift($Requetes,array('query'=>"SET collation_connection = 'utf8_general_ci'"));
		
		foreach($Requetes as $sqlTb) {
            try{
              $this->Resultat = mysql_query ($sqlTb['query'], $this->Connexion);
              $this->_debug($sqlTb['query']);
            } catch (Exception $e){
              $mes = $e->getMessage();
              
            }
		}
	}

	function _insertUpdateDelete($sql){
		if(str_replace(' ','',$sql)==''){
			$this->Count=0;
			return 0;
		}
		$this->_query($sql);
		$this->Count	= 	@mysql_affected_rows($this->Connexion);
		return $this->Resultat;
	}
	
	function Insert($sql){
		$ret= $this->_insertUpdateDelete($sql);
		$this->lastId	=	$this->getLastID();
		return $ret;
	}
	
	function Delete($sql){
		return $this->_insertUpdateDelete($sql);
	}

	function Update($sql){
		return $this->_insertUpdateDelete($sql);
	}

	function Select($sql){
		if(str_replace(' ','',$sql)==''){
			$this->Count=0;
			return 0;
		}
			
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		return $this->Resultat;
	}

	// Retourne toutes les lignes de la requete dans un tableau 
	function SelectAll($sql){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		$ret = array();
        
		while($row=$this->Next())
			$ret[]=$row;
			
		return $ret;
	}

	// Retourne toutes les lignes de la requete dans un tableau 
	function SelectAllBy($sql,$by){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		
		$by=explode(',',$by);

        $ret = array();
		
		while($row=$this->Next()){
			switch(count($by)){	
			case 1:
				$ret[$row[$by[0]]]=$row;
				break;
			case 2:
				$ret[$row[$by[0]]][$row[$by[1]]]=$row;
				break;
			case 3:
				$ret[$row[$by[0]]][$row[$by[1]]][$row[$by[2]]]=$row;
				break;
			case 4:
				$ret[$row[$by[0]]][$row[$by[1]]][$row[$by[2]]][$row[$by[3]]]=$row;
				break;
			}
		}
			
		return $ret;
	}

    	// Retourne toutes les lignes de la requete dans un tableau 
	function SelectAllByToObject($sql,$by,$className){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		
		$by=explode(',',$by);

        $ret = array();
		
		while($row=$this->Next()){
            $obj = new $className($row);
			switch(count($by)){	
			case 1:
				$ret[$row[$by[0]]]=$obj;
				break;
			case 2:
				$ret[$row[$by[0]]][$row[$by[1]]]=$obj;
				break;
			case 3:
				$ret[$row[$by[0]]][$row[$by[1]]][$row[$by[2]]]=$obj;
				break;
			case 4:
				$ret[$row[$by[0]]][$row[$by[1]]][$row[$by[2]]][$row[$by[3]]]=$obj;
				break;
			}
		}
			
		return $ret;
	}


	// Retourne le premier résultat de la requête $Requete 
	function SelectFirst($sql){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		
		if($this->Count)
          try{
			$ret=$this->Next();
          } catch(Exception $e){
            $e;
          }
		else
			$ret=Array();
				
		return $ret;
	}

	
	// Retourne un tableau contanant toutes les colonnes col de la requête
	function SelectCol($sql,$col){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		$ret            = array();
        
		while($row=$this->Next())
			$ret[]=$row[$col];
			
		return $ret;
	}

    // Retourne le premier résultat de la requête $Requete 
	function SelectFirstCol($sql,$col){
		$ret = $this->SelectFirst($sql);
        
        if(isset($ret) && isset($ret[$col])){
          $ret = $ret[$col];
        }
        
		return $ret;
	}
	
	function Count($sql){
		$this->_query($sql);
		$this->Count	= @mysql_num_rows($this->Resultat);
		$row=$this->Next(MYSQL_BOTH);
		return $row[0];
	}
	
	function getErrno(){
		return mysql_errno($this->Connexion);	
	}
	
	function getError(){
		return mysql_error($this->Connexion);	
	}

	function encodeUTF8(&$row){
		if($this->UTF8!=true)
			return;

		if(is_array($row)){
			array_walk($row,array('self', 'enc_utf8'));
		}
	}

    function decodeUTF8(&$row){
		if($this->UTF8!=true)
			return;

		if(is_array($row)){
			array_walk($row,'dec_utf8');
		}
	}

	function Next($fetch_Mode = MYSQL_ASSOC){
      try{
        $row=mysql_fetch_array($this->Resultat,$fetch_Mode);
        return self::stripslashes_sql($row);
      }catch(Exception $e){
        $e;
      }
	}
	function getRowByNames(){

		return mysql_fetch_object($this->Resultat);

	}
	
	function getRowByIds(){

		return mysql_fetch_row($this->Resultat);

	}

	function getLastID(){
		return mysql_insert_id($this->Connexion);
	}
	
	function RecordCount(){
		return mysql_num_rows($this->Resultat);
	}
	
	function getRowNames($tablename,$exclude){
		
//		$this->Resultat = @mysql_list_fields($this->dbName,$tablename);//,$this->Connexion);
		$this->Resultat = mysql_query("SHOW COLUMNS FROM $tablename");
//		$count = @mysql_num_fields($this->Resultat);

		$retour = array();
		if($this->Resultat){
          while($row = mysql_fetch_array($this->Resultat)){
                if(!in_array($row['Field'],$exclude))
					$retour[]=$row['Field'];
				elseif(!isset($exclude))
					$retour[]=$row['Field'];
			}
		}

		return $retour;
			
	}

/**************************************
*
**************************************/
	function extractFields($tbl,$fieldName=''){
		
		if($fieldName=='')
			$fieldName='field';
		
		if(!isset($tbl[$fieldName]) || !is_array($tbl[$fieldName]))
			return null;

		foreach($tbl[$fieldName] as $key=>$val)
			foreach($tbl[$fieldName][$key] as $idx=>$val1)
				$fields[$idx][$key]=$val1;
		
		return $fields;	
	}

	function createCompareUpdate($table,$new_values,$old_values,$where=''){
		// Left contient les nouvelles modifs, right contient les anciennes valeurs 
		$update=false;
		$sql='Update '.$table.' set';

		if(!is_array($new_values) && !is_array($old_values))
			return ;
		
		if(!is_array($new_values))
			$new_values=array();

		if(!is_array($old_values))
			$old_values=array();
			
		
		foreach($new_values as $key=>$val){
			if($val!=$old_values[$key]){
				$sql.=' '.$key.'="'.$val.'",';
				$update=true;
			}
		}

		foreach($old_values as $key=>$val){
		
			if(!isset($new_values[$key])){
				// Pas setté dnas le $_POST c'est sans doute un checkbox dévalidé
				$sql.=' '.$key.'=false,';
				$update=true;
			}
		}

        if(!empty($where)){
          $sql=substr($sql,0,-1)." where $where";
        }
		
		if($update)
			return $sql;
		else
			return " ";
		
	}


function InsertSQL($tablename,$tbl){
	global $db;
	
	$fieldList=$db->getRowNames($tablename,array());
	
	$fieldList=array_flip($fieldList);
	while(list($id1,$id2) = each($fieldList)){
		if(isset($tbl[$id1]))
			$v[$id1]=$tbl[$id1];
	}
	$fieldList=$v;
	
	$SQL="INSERT INTO `$tablename` (";
    $SQL2='';
	
	reset($fieldList);
	
	while(list($name,$value) = each($fieldList)){
		$SQL.="`$name`,";
		$SQL2.='"'.$value.'",';
	}
	
	$SQL=substr($SQL,0,-1).') VALUES('.substr($SQL2,0,-1).');';
	
	return $SQL;
	
}

function UpdateSQL($tablename,$tbl,$where=''){
	global $db;
	
	$fieldList=$db->getRowNames($tablename,array());
	
	$fieldList=array_flip($fieldList);
	
	foreach($fieldList as $id1=>$id2){
		if(isset($tbl[$id1])){
			$v[$id1]=$tbl[$id1];
        }
	}
	$fieldList=$v;
	
	$SQL="UPDATE `$tablename` SET ";
	
	reset($fieldList);
    
    foreach($fieldList as $key=>$value){
      $SQL.="`$key`=\"$value\",";
    }
		
	$SQL=substr($SQL,0,-1);
	
	if(!empty($where))
		$SQL.=" where $where";
		
	return $SQL.';';
	
}

	function createWhereSQL($filter,$cond='AND'){
		$sql='';
		$sqlbefore='';
		foreach($filter as $champ=>$val){
			$sqlbefore=$sql;

			if($sql!='') $sql.=" $cond ";
			if($sql=='') $sql='where ';

			$sql.=$champ;

			if(is_array($val)){
				$sql.=' in (';

				foreach($val as $value){
					if($value=='*'){
						$sql=$sqlbefore;
						break;
					}
					if($value=='') 	$sql=$sqlbefore;
					else			$sql.='"'.$value.'",';
				}

				$sql=substr($sql,0,-1); //pour shunter la virgule

				$sql.=')';
			}
			else{
				if($val=='') 	$sql=$sqlbefore;
				else			$sql.='="'.$val.'"';

				if($val=='*')
					$sql=$sqlbefore;

			}
		}
		return $sql;
	}
	
	function getMySQLInfo(){
		return mysql_get_server_info($this->Connexion);
	}
    
    private function _prefixTables(&$sql){
      $sql1=$sql;
      
      $tables = self::getTablesNames();
      $prefix = self::getTablePrefix();
      if(is_array($tables) && count($tables)>0){
        foreach ($tables as $key=>$val){
          if(is_null($key) ||!is_string($key)){
            $key = $val;
            $val = null;
          }
          if(is_null($val) || empty ($val)){
            $val = $prefix.$key;
          }
          $key  = "/(?<!$prefix)$key/";
          $sql1 = preg_replace($key, $val, $sql1);
        }
      }
              
      $sql=$sql1;
    }
    
	// Fonctio de PHP ADMIN dans la cas de plusieurs commandes sql dans la même requete
	function PMA_splitSqlFile(&$ret, &$sql)//, $release)
	{
      
        $this->_prefixTables($sql);
	    // do not trim, see bug #1030644
	    //$sql          = trim($sql);
	    $sql          = rtrim($sql, "\n\r");
	    $sql_len      = strlen($sql);
	    $char         = '';
	    $string_start = '';
	    $in_string    = FALSE;
	    $nothing      = TRUE;
	    $time0        = time();
	
	    for ($i = 0; $i < $sql_len; ++$i) {
	        $char = $sql[$i];
	
	        // We are in a string, check for not escaped end of strings except for
	        // backquotes that can't be escaped
	        if ($in_string) {
	            for (;;) {
	                $i         = strpos($sql, $string_start, $i);
	                // No end of string found -> add the current substring to the
	                // returned array
	                if (!$i) {
	                    $ret[] = array('query' => $sql, 'empty' => $nothing);
	                    return TRUE;
	                }
	                // Backquotes or no backslashes before quotes: it's indeed the
	                // end of the string -> exit the loop
	                else if ($string_start == '`' || $sql[$i-1] != '\\') {
	                    $string_start      = '';
	                    $in_string         = FALSE;
	                    break;
	                }
	                // one or more Backslashes before the presumed end of string...
	                else {
	                    // ... first checks for escaped backslashes
	                    $j                     = 2;
	                    $escaped_backslash     = FALSE;
	                    while ($i-$j > 0 && $sql[$i-$j] == '\\') {
	                        $escaped_backslash = !$escaped_backslash;
	                        $j++;
	                    }
	                    // ... if escaped backslashes: it's really the end of the
	                    // string -> exit the loop
	                    if ($escaped_backslash) {
	                        $string_start  = '';
	                        $in_string     = FALSE;
	                        break;
	                    }
	                    // ... else loop
	                    else {
	                        $i++;
	                    }
	                } // end if...elseif...else
	            } // end for
	        } // end if (in string)
	
	        // lets skip comments (/*, -- and #)
	        else if (($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*')) {
	            $i = strpos($sql, $char == '/' ? '*/' : "\n", $i);
	            // didn't we hit end of string?
	            if ($i === FALSE) {
	                break;
	            }
	            if ($char == '/') $i++;
	        }
	
	        // We are not in a string, first check for delimiter...
	        else if ($char == ';') {
	            // if delimiter found, add the parsed part to the returned array
	            $ret[]      = array('query' => substr($sql, 0, $i), 'empty' => $nothing);
	            $nothing    = TRUE;
	            $sql        = ltrim(substr($sql, min($i + 1, $sql_len)));
	            $sql_len    = strlen($sql);
	            if ($sql_len) {
	                $i      = -1;
	            } else {
	                // The submited statement(s) end(s) here
	                return TRUE;
	            }
	        } // end else if (is delimiter)
	
	        // ... then check for start of a string,...
	        else if (($char == '"') || ($char == '\'') || ($char == '`')) {
	            $in_string    = TRUE;
	            $nothing      = FALSE;
	            $string_start = $char;
	        } // end else if (is start of string)
	
	        elseif ($nothing) {
	            $nothing = FALSE;
	        }
	
	        // loic1: send a fake header each 30 sec. to bypass browser timeout
	        $time1     = time();
	        if ($time1 >= $time0 + 30) {
	            $time0 = $time1;
	            header('X-pmaPing: Pong');
	        } // end if
	    } // end for
	
	    // add any rest to the returned array
	    if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
	        $ret[] = array('query' => $sql, 'empty' => $nothing);
	    }
	
	    return TRUE;
	} // end of the 'PMA_splitSqlFile()' function
	
	
	function _debug($Requete){
		if(DEBBUG_SQL && mysql_errno($this->Connexion)!=0){
	        echo '
	            <table 
	                align="left" 
	                border="1" 
	                style="
	                    position: absolute; 
	                    background-color: gray;
	                    color: white;
	                    border: 2px solid black;
	                "
	                cellpadding="0"
	                cellspacing="1"
	                onclick="
	                	if(!event)
	                		event=window.event;
	                	if(!event.shiftKey)
	                		return true;
	                		
	                    this.setAttribute(\'reduce\',(this.getAttribute(\'reduce\')==\'true\' ? \'false\' : \'true\')); 
	                    this.style.fontSize=(this.getAttribute(\'reduce\')==\'true\' ? \'1\' : \'\');
	                    this.style.width=(this.getAttribute(\'reduce\')==\'true\' ? \'10px\' : \'\');
	                    
	                "
	                    >
	                <tr>
	                    <th colspan="4">
	           				/******************* SQL Error *****************************&nbsp;&nbsp;&nbsp;<font size="1">(shift+clic pour basculer)</font>
	                    </th>
	                </tr>
	                <tr>
	                    <td colspan="1" style="padding: 5px;">SQL</td>
	                    <td colspan="3" style="padding: 5px;">'.$Requete.'</td>
	                </tr>
	                <tr>
	                    <td style="padding: 5px;">N&deg;</td>
	                    <td style="padding: 5px;">'.mysql_errno($this->Connexion).'</td>
	                    <td style="padding: 5px;">Desc</td>
	                    <td style="padding: 5px;">'.mysql_error($this->Connexion).'</td>
	                </tr>
	            </table><br>';
	        exit;
	    }
	}
}

?>
